class Solution {
    int ret, m, n;
    bool visited[15][15];
    // vector<pair<int, int>> dir = { {0, -1}, {0, 1}, {1, 0}, {-1, 0} };      // 四个方向
    int dx[4] = { 0, 0, -1, 1 }, dy[4] = { -1, 1, 0, 0 };
    void dfs(vector<vector<int>>& grid, int i, int j, int path)
    {
        ret = max(ret, path);

        for(int k = 0; k < 4; k++)
        {
            // int x = i + dir[k].first, y = j + dir[k].second;
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] != 0 && visited[x][y] == false)
            {
                visited[x][y] = true;
                dfs(grid, x, y, path + grid[x][y]);
                // 恢复现场
                visited[x][y] = false;
            }
        }
    }
public:
    int getMaximumGold(vector<vector<int>>& grid) {
        m = grid.size(), n = grid[0].size();
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(grid[i][j] != 0)
                {
                    visited[i][j] = true;
                    dfs(grid, i, j, grid[i][j]);
                    // 恢复现场
                    visited[i][j] = false;
                }
            }
        }
        return ret;
    }
};